package com.sea.finance.controller;

import com.codecrane.core.power.service.DictDetailService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sea.supply.entity.ProducePayment;
import com.sea.supply.service.ProducePaymentService;
import com.sea.supply.service.ProduceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/sea/finance/produce/payment")
public class FinanceProducePaymentController {

    @Autowired
    private ProduceService produceService;
    @Autowired
    private ProducePaymentService producePaymentService;
    @Autowired
    private DictDetailService dictDetailService;
    /**
     * 管理主页面
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("payment", dictDetailService.findByTypeCode("payment_type", null));
        return "/sea/finance/producePayment/main";
    }



    /**
     * 分页条件查询
     *
     * @param pagesize
     * @param start
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     ProducePayment producePayment) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<ProducePayment> list = producePaymentService.findByCnd(producePayment);
        PageInfo<ProducePayment> page = new PageInfo<>(list);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 生成采购单
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/pay", method = RequestMethod.POST)
    public AjaxReturn produce(@RequestParam("payIds")Integer[]payIds, @RequestParam("producePayTime")String producePayTime,String produceFile) {
        AjaxReturn result = Ajax.fail().setMsg("生成失败！");
        try{
            if (null != payIds && StringUtils.isNotEmpty(producePayTime)) {
                producePaymentService.pay(payIds, producePayTime,produceFile);
                result.setOk(true).setMsg("生成成功！");
            }
        }catch (RuntimeException e){
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e){
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, ProducePayment producePayment) {
        List<ProducePayment> list = producePaymentService.findByCnd(producePayment);
        String[] title = {"采购单号","供应商","付款金额","币种",
                "付款信息","核销状态","核销金额","杂项费",
                "实际需付款","付款状态","付款金额","付款凭证","收具发票","发票凭证","渠道",
                "申请付款时间","实际付款时间","出货时间","柜号","备注","合同号","付款备注(表头)","付款状态(表头)","付款类型","账期"};
        String fileName = "付款信息表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "付款信息表";
        String[][] content = new String[list.size()][25];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            ProducePayment obj = list.get(i);
            content[i][0] = obj.getProduceNo();
            content[i][1] = obj.getProduceSupplierName();
            content[i][2] = obj.getProducePayment()+"";
            content[i][3] = obj.getProduceMoneyType();
            content[i][4] = obj.getProduceRemark();
            content[i][5] = obj.getProduceIsCheck()+"";
            content[i][6] = obj.getProduceCheckMoney()+"";
            content[i][7] = obj.getProduceUnusualMoney()+"";
            if(null==obj.getProduceUnusualMoney()){
                content[i][8] = (obj.getProducePayment()-obj.getProduceCheckMoney()-0)+"";
            }else {
                content[i][8] = (obj.getProducePayment() - obj.getProduceCheckMoney() - obj.getProduceUnusualMoney()) + "";
            }
            Integer flag = obj.getFlag();
            if(flag==1){
                content[i][9] = "已付款";
            }else{
                content[i][9] = "未付款";
            }
            content[i][10] = obj.getProducePay()+"";
            content[i][11] = obj.getProduceFile();
            content[i][12] = obj.getProduceIsBill()+"";
            content[i][13] = obj.getProduceBillFile();
            content[i][14] = obj.getOrderChannelName();
            content[i][15] = obj.getCreateTime();
            content[i][16] = obj.getProducePayTime();
            content[i][17] = obj.getProduceOutTime();
            content[i][18] = obj.getCreatePlanNo();
            content[i][19] = obj.getProduceReason();
            content[i][20] = obj.getProduceAgreement();
            content[i][21] = obj.getProducePaymentRemark();
            Integer status = obj.getProducePaymentStatus();
            if(null !=status && status==1){
                content[i][22] = "无异常";
            }else{
                content[i][22] = "";
            }
            content[i][23] = obj.getPaymentType();
            if(null==obj.getSupplierDay()){
                content[i][24] = 0+"";
            }else{
                content[i][24] = obj.getSupplierDay()+"";
            }

        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
